<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Recipients extends CI_Controller {


	function __construct(){

		parent::__construct();
		if(!isset($_SESSION)): session_start(); endif;
		(isset($_SESSION['is_logged_in']) && $_SESSION['is_logged_in'] && isset($_SESSION['email']))? '':redirect('home');
		$this->load->model('recipients_model');
		$this->load->model('users_model');
		//$this->load->helper('encryption_helper');

	}



	public function index(){

		$post = $this->input->post();
		$start_row = $this->uri->segment(3);
		$this->page($start_row,$post);
	}
	function page($start_row='',$post=''){

		$search = '';
		if(!empty($post)){
			$r_search = $post['r-search'];
			if(!empty($r_search)){
				switch($post['search-list']){
					case 1: $search =" AND fname LIKE '%$r_search%'";break;//first name
					case 2: $search =" AND lname LIKE '%$r_search%'";break;//last name
					case 3: $search =" AND mname LIKE '%$r_search%'";break;//middlename
					default:$search =" AND (fname LIKE '%$r_search%' OR lname LIKE '%$r_search%' OR mname LIKE '%$r_search%')";break;
				}
			}
		}
		$data['recipients_all'] = $this->recipients_model->getRecipients($search);
		$limit = 5; //result per page
		if(trim($start_row) == ""){
			$start_row = 0;
		}
		$data['recipients'] = $this->recipients_model->getRecipients($search,$start_row,$limit);
		$this->load->library('pagination');
		$config['base_url'] = site_url('recipients/page/');
		$config['total_rows'] = count($data['recipients_all']);
		$config['per_page'] = $limit;
		$config['uri_segment'] = 3;
		$config['anchor_class'] = 'class="button pagi" ';
		$this->pagination->initialize($config);
		$data['pagination'] = $this->pagination->create_links();
		$data['title']= "Recipients";
		$data['records'] 		= $this->users_model->get_user();//added code
		if($search == ''){
			$data['main_content'] = 'profile/recipients_view';
			$this->load->view('include/template', $data);
		}else{
			$output = '';
			$output .= '<div class="pagination">'.$data['pagination'].'</div>';
			$output .= '<div class="clear"></div>';
			$output .= '<div class="notice"></div>';
			$output .= '<input type="hidden" id="path" name="path" value="'.base_url().'"/>';
			foreach ($data['recipients'] as $row){
				$user_id = urlencode($this->encryption_lib->encode($row->recipientid));
				$output .= '<div id = "recipient-context_"'.$user_id.'" class="recipient-context">';
					$output .= '<label>'.$row->fname.'&nbsp;'.$row->lname.'</label>';
					$output .= '<p>'.$row->address.'</p>';
					$output .= '<p>'.$row->phone.'</p>';
					$output .= '<div id = "recipient-control">';
						$output .= '<a href = "javascript:void(0);" onclick="edit_recipient('.$user_id.')">';
						$output .= '<img src = "'.base_url().'"assets/images/edit-btn.png" alt = "" /></a> &nbsp;&nbsp;&nbsp;';
						$output .= '<a href = "javascript:void(0)" onclick="deleteRecipient('.$user_id.')">';
						$output .= '<img src = "'.base_url().'"assets/images/trash-can.png" alt = "" /></a>&nbsp;&nbsp;';
					$output .= '</div>';
				$output .= '</div>';
			}//end foreach
			echo $output;
		}

	}


	function type()
	{
		$data['recipients'] = $this->recipients_model->getRecipients();
		$data['records'] = $this->users_model->get_user();
		$data['title']= "Receptients";
		$data['main_content'] = 'profile/recipients_type_view';


		$this->load->view('include/template', $data);

	}


	function create_recipients(){
		$query = $this->recipients_model->addRecipients();
		$executorField = $this->input->post('is_executor');
		if(($query) && (!empty($executorField))){
			$send = $this->sendPassword($this->input->post('add-recep-email'));

			//echo ($send) ? 'send' : 'wla m-send';
		}
		echo ($query)? 'true':'false';
		return $query;

	}

	function delete_recipients(){
		$id = $this->input->post('rec_id');
		$rec_id = urldecode($this->encryption_lib->decode($id));
		$delete = $this->recipients_model->delete_recipient($rec_id);
		echo ($delete)? '1':'0';//1 - successfull 0 - unsucessfull
	}
	function edit_recipient(){
		$output = '';
		$id = $this->input->post('rec_id');
		$rec_id = urldecode($this->encryption_lib->decode($id));
		$rec_info = $this->recipients_model->get_recipient_info($rec_id);
		$relationships = $this->recipients_model->get_relationships();
		$checked = ($rec_info['is_executor']==1) ? 'checked="checked"' : '';
		$output .= '<input type = "hidden" value = "'.$id.'" name = "edit-recep-id" id = "edit-recep-id" />';
		$output .= '<p class = "add-recep"><input type = "text" value = "'.$rec_info['fname'].'" name = "add-recep-fname" id = "add-recep-fname" /></p>';
		$output .= '<p class = "add-recep"><input type = "text" value = "'.$rec_info['mname'].'" name = "add-recep-mname" id = "add-recep-mname" /></p>';
		$output .= '<p class = "add-recep"><input type = "text" value = "'.$rec_info['lname'].'" name = "add-recep-lname" id = "add-recep-lname" /></p>';
		$output .= '<p class = "add-recep">';
			$state = (empty($rec_info['state']))? 'State':$rec_info['state'];
			$output .= '<input type = "text" value = "'.$state.'" name = "add-recep-state" id = "add-recep-state"/>';
		$output .= '</p>';
		$output .= '<p>';
			$city = (empty($rec_info['city']))? 'City':$rec_info['city'];
			$zip = (empty($rec_info['zip']))? 'Zip':$rec_info['zip'];
			$output .= '<input type = "text" value = "'.$city.'" name = "add-recep-city" id = "add-recep-city"/>';
			$output .= '<input type = "text" value = "'.$zip.'" name = "add-recep-zip" id = "add-recep-zip"/>';
			$output .= '<div class="cboth"></div>';
		$output .= '</p>';
		$output .= '<p class = "add-recep">';
			$output .= '<label>Relationship</label>';
			$output .= '<select name="add-recep-rel">';
				foreach($relationships as $rel):
					$selected = ($rec_info['relationship'] == $rel['id'])? 'selected="selected"':'';
					$output .= '<option value="'.$rel['id'].'"'.$selected.'>'.$rel['title'].'</option>';
				endforeach;
			$output .= '</select>';
		$output .= '</p>';
		$output .= '<p class = "add-recep"><input type = "text" value = "'.$rec_info['phone'].'" name = "add-recep-phone" id = "add-recep-phone" /></p>';
		$output .= '<p class = "add-recep"><input type = "text" value = "'.$rec_info['email'].'" name = "add-recep-email" id = "add-recep-email" /></p>';
		$output .= '<p>Set As Executor:<input type="checkbox" value="1" name="is_executor" '.$checked.'/></p>';
		echo $output;
	}
	function update_recipient(){
		$post = $this->input->post();
		$update = $this->recipients_model->update_recipient($post);
		$executorField = $this->input->post('is_executor');
		if(($update) && (!empty($executorField))){
			 $this->sendPassword($this->input->post('add-recep-email'));
		}
		echo ($update)? '1':'0';
	}
	function check_email_exist(){
		$email = $this->input->post('email');
		$exist = $this->recipients_model->check_email_recipient_exist($email);
		echo ($exist)? '1':'0';
	}
	function add_recipients(){
		$data['recipients'] = $this->recipients_model->getRecipients();
		$data['relationships'] = $this->recipients_model->get_relationships();
		$data['records'] = $this->users_model->get_user();
		$data['title']= "My Life My Eulogy | Add Recipients";
		$data['main_content'] = 'profile/add_recipients_type_view';
		$this->load->view('include/template', $data);
	}

	function sendPassword($send_to=''){

		//$this->load->library('encrypt');
		$this->load->model('lib_model');
		$getSessionEmail = $_SESSION['email'];

		//get profiler/user info
		$getPassword = $this->lib_model->get('mlme_users','password_recipient,password_executor,lastname,firstname,middle','email',$getSessionEmail);

		$toDecodeRecipientPass = $getPassword[0]->password_recipient;
		$toDecodeExecutorPass  = $getPassword[0]->password_executor;
		$executor_password     = $this->encryption_lib->decode($toDecodeExecutorPass);
		$profiler_name = $getPassword[0]->firstname.' '.$getPassword[0]->middle.' '.$getPassword[0]->lastname;

		$executor_name = $this->input->post('add-recep-fname').' '.$this->input->post('add-recep-mname').' '.$this->input->post('add-recep-lname');

		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= "From: My Life My Eulogy <lalene@advanzweb.com> \r\n";
		$subject  = "My Life My Eulogy - Executor's and Recipient Password";

		$registerLink='<a href="'.base_url().'register/free'.'">Click here to register.'.'</a>';
		$loginLink   ='<a href="'.base_url().'"> Click here to login'.'</a>';
		$body='';
		$body.='Hi <b>'.$executor_name.'</b>,';
		$body.="<br/><br/>You have chosen as one of the executors of <strong>".ucwords($profiler_name)."\'s</strong> Eulogy";
		$body.='<br/><br/>Please visit My Life My Eulogy Website:';
		$body.='<br/><br/>No account yet? '.$registerLink;
		$body.='<br/>Already have an account? '.$loginLink;

		$body.="<br/></br/></br/>Follow these steps to access <strong>".ucwords($profiler_name)."'s</strong> eulogy profile and to notify his/her recipients.";
		$body.="<ol>";
		$body.="<li>Login to MLME Website with your own account.</li>";
		$body.="<li>Click on the executor section located at the upper right corner of your profile page.</li>";
		$body.="<li>Look for the eulogy profile name and enter the following password code: <strong>".$executor_password."</strong></li>";
		$body.="<li>***Please note that this code cannot be modified. You need to print this information in case you forgot it.</li>";
		$body.="<li>Once you click Notify all recipients, and at least 2 executors wiil confirm that this profiler has already passed away, the recipients will be notified and will come to MLME to view his/her eulogy profile and the messages sent for them as well as the Eulogy Video to be viewed at his/her wake.</li>";
		$body.="</ol>";

		return (mail($send_to, $subject, $body,$headers)) ? true : false;


	}//end fct

	//for recipient notification
	function notification(){
		$this->load->model('lib_model');
		$encryptedId = $this->input->post('userId');
		$userId = $this->encryption_lib->decode($encryptedId);
		$userInfo = $this->lib_model->get('mlme_users','firstname,lastname,middle,userid','userid',$userId);
 	    $data['userId']= $userInfo[0]->userid;
		$data['ProfileName'] = $userInfo[0]->firstname.' '.$userInfo[0]->lastname;
		$this->load->view('notification',$data);
	}//end fct

	//evaluate notification
	function evaluateNotification(){
		$this->load->model('lib_model');
		$ProfilerId = $this->input->post('notified_id');
		$getData = $this->lib_model->get('mlme_users','*','userid',$ProfilerId);
		$getUserData 	 = $this->lib_model->get('mlme_users','userid','email',$_SESSION['email']);
		$userId = $getUserData[0]->userid;

		$columnNotifiedBy = $getData[0]->notified_by;
		if(!empty($columnNotifiedBy)){
			$explodedData 		= explode(',',$columnNotifiedBy);
			//foreach
			$countData = 0;
			foreach($explodedData as $xdata){
				if(!empty($xdata)){
					$countData++;
				}
			}
			if($countData >= 2){
				//send notification to all recipient
				$this->sendNotification($ProfilerId);

			}else{
				$inArray = in_array($userId,$explodedData);
				if(!$inArray){
					$this->updateNotifiedBy($ProfilerId);
					$this->sendNotification($ProfilerId);//
				}else{
					echo 'need';exit;
				}
			}
		}else{
			$this->updateNotifiedBy($ProfilerId);
		}
	}//end fct

	//update column notified by
	function updateNotifiedBy($ProfilerId){
		$this->load->model('lib_model');
		$getProfilerData = $this->lib_model->get('mlme_users','notified_by','userid',$ProfilerId);
		$getUserData 	 = $this->lib_model->get('mlme_users','userid','email',$_SESSION['email']);
		$userId = $getUserData[0]->userid;
		$columnNotifiedBy = $getProfilerData[0]->notified_by;
		$concatenatedData = !empty($columnNotifiedBy)	?	$columnNotifiedBy.$userId.','	:	$userId.',';
		$data2Update = array('notified_by'=>$concatenatedData);

		$update = $this->lib_model->update('mlme_users','userid',$ProfilerId,$data2Update);
		return ($update)	?	TRUE	:	FALSE;


	}//end fct

	//send notification to all recipients'
	function sendNotification($notifiedId){
		$this->load->model('lib_model');
		//$notifiedId = $this->input->post('notified_id');
		$getNotifiedInfo = $this->lib_model->get('mlme_users','firstname,lastname','userid',$notifiedId);

		$getAllRecipients = $this->recipients_model->getAllRecipientsEmail($notifiedId);
		//echo $notifiedId;exit;

		if(!empty($getNotifiedInfo)){
			$profilerName = $getNotifiedInfo[0]->firstname.' '.$getNotifiedInfo[0]->lastname;
		}
		if(!empty($getAllRecipients)){
			//mail
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
			$headers .= "From: My Life My Eulogy <lalene@advanzweb.com> \r\n";
			$subject  = "My Life My Eulogy - Notification";
			$body     ='';
			//
			foreach($getAllRecipients as $recipients){
				$recipientName = ucfirst($recipients['fname']).' '.ucfirst($recipients['lname']);
				$body	 .='Hi <b>'.$recipientName.',</b>';
				$body	 .='<br/>You have notified the death of Mr.'.$profilerName;
				$send_to=$recipients['email'];
				mail($send_to, $subject, $body,$headers);
			}
			echo 'true';
		}else{
			echo 'false';
		}

	}
}// end of controller
